package REVIEW2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket=null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器已经启动");
        ExecutorService executorService= Executors.newCachedThreadPool();
        while(true){
            Socket cilentSocket=serverSocket.accept();
            executorService.submit(()->{
                try {
                    processconnection(cilentSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }
    private void processconnection(Socket cilentSocket) throws IOException {
        System.out.printf("客户端已经上线,%s,%d\n",cilentSocket.getInetAddress(),cilentSocket.getPort());

        try(InputStream inputStream=cilentSocket.getInputStream();
            OutputStream outputStream=cilentSocket.getOutputStream()){
            Scanner scanner=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("客户端已经下线,%s,%d\n",cilentSocket.getInetAddress(),cilentSocket.getPort());
                    break;
                }
                //1.读取请求
                String request=scanner.next();
                //2.根据请求，计算响应
                String response=process(request);
                //3.发送响应给服务器
                printWriter.println(response);
                printWriter.flush();
                //4.打印日志
                System.out.printf("%s,%d,%s,%s\n",cilentSocket.getInetAddress(),cilentSocket.getPort(),request,response);
            }
        }finally {
            cilentSocket.close();
        }
    }
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(7777);
        tcpEchoServer.start();



    }
}
